import { noop } from 'lodash'

export default new Promise(resolve => {
  if (/ios/i.test(navigator.userAgent)) {
    ((callback) => {
      if (window.WebViewJavascriptBridge) { return callback(window.WebViewJavascriptBridge) }
      if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback) }
      window.WVJBCallbacks = [callback]
      const WVJBIframe = document.createElement('iframe')
      WVJBIframe.style.display = 'none'
      WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'
      document.documentElement.appendChild(WVJBIframe)
      setTimeout(() => { document.documentElement.removeChild(WVJBIframe) }, 0)
    })(resolve)
  } else {
    ((w, cb) => {
      if (w.WebViewJavascriptBridge) {
        cb(w.WebViewJavascriptBridge)
      } else {
        w.document.addEventListener('WebViewJavascriptBridgeReady', () => {
          cb(w.WebViewJavascriptBridge)
        }, false)
      }
    })(window, bridge => {
      resolve(bridge)
      if (!bridge.initalized) {
        bridge.initalized = true // 防止bridge多次初始化报错
        bridge.init(noop)
      }
    })
  }
})
